package com.colorlight.cloud.complete.entity.event;

import com.colorlight.cloud.complete.api.CompleteEntityEvent;
import com.colorlight.cloud.complete.entity.po.ResultItem;
import com.colorlight.iot.proto.complete.event.CompleteEvent;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 执行异常结果上报
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class ExecuteUpload implements CompleteEntityEvent {

    /**
     * 指令类型
     */
    private Integer type;

    /**
     * 执行失败结果
     */
    private List<ResultItem> resultItem;

    /**
     * 指令消息流水号
     */
    private Long seqId;

    @Override
    public ExecuteUpload byteConvertObject(ByteString bytes) {
        CompleteEvent.ExecuteUpload executeUpload = null;
        try {
            executeUpload = CompleteEvent.ExecuteUpload.parseFrom(bytes);
        } catch (InvalidProtocolBufferException e) {
            log.error("", e);
        }
        Objects.requireNonNull(executeUpload);
        this.setType(executeUpload.getType());
        this.setSeqId(executeUpload.getSeqId());
        List<ResultItem> collect = executeUpload.getResultItemList().stream().map(e -> new ResultItem().formProto(e)).collect(Collectors.toList());
        this.setResultItem(collect);
        return this;
    }
}

